package com.xc.freeapp.util;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xc.freeapp.entity.UserInfo;

public class JsonUtil {
	protected final static Log log =LogFactory.getLog(JsonUtil.class);
    /**
     * 私有化构造方法
     */
    private JsonUtil() {
    }
    /****
     * 将object转换成json数据
     * @param obj
     * @return
     */
  public static String object2json(Object obj) {
      StringBuilder json = new StringBuilder();
      if (obj == null) {
        json.append("\"\"");
      } else if (obj instanceof String || obj instanceof Integer || obj instanceof Float
          || obj instanceof Boolean || obj instanceof Short || obj instanceof Double
          || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger
          || obj instanceof Byte) {
        json.append("\"").append(string2json(obj.toString())).append("\"");
      } else if (obj instanceof List) {
        json.append(list2json((List<?>) obj));
      } 
      else {
          json.append(toJson(obj));
        }
      return json.toString();
    }  
  /****
   * 这个方法是将实体bean转换成json
   * @param bean
   * @return
   */
  public static String bean2json(Object bean) {
      StringBuilder json = new StringBuilder();
      json.append("{");
      PropertyDescriptor[] props = null;
      try {
        props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();
      } catch (IntrospectionException e) {}
      if (props != null) {
        for (int i = 0; i < props.length; i++) {
          try {
            String name = object2json(props[i].getName());
            String value = object2json(props[i].getReadMethod().invoke(bean));
            json.append(name);
            json.append(":");
            json.append(value);
            json.append(",");
          } catch (Exception e) {}
        }
        json.setCharAt(json.length() - 1, '}');
      } else {
        json.append("}");
      }
      return json.toString();
   }
    /**
     * 将Object转换成JSON串
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        String json = "";
        if (obj != null) {
            try {
                json = JSON.toJSONString(obj);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return json;
    }
    
    /**
     * 将JSON字符串转换成对象
     * 
     * @param json  要解析的JSON字符串
     * @param cls   要解析成的对象类型
     * @return
     */
    public static <T> T parseJson(String json, Class<T> cls) {
        T t = null;
        try {
            t = JSON.parseObject(json, cls);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return t;
    }
    
    /**
     * 将JSON转成List数据集
     * 
     * @param json  JSON字符串
     * @param cls  要解析成的对象类型
     * @return
     */
    public static <T> List<T>parseList(String json, Class<T> cls) {
        List<T> lst = new ArrayList<T>();
        try {
            
            lst = (List<T>) JSON.parseArray(json, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lst;
    }
    
    /**
     * 将JSON串解析成List<Map<String, Object>>
     * 
     * @param jsonString
     * @return
     */
    public static List<Map<String, Object>> parseListMap(String jsonString) {
        List<Map<String, Object>> lst = new ArrayList<Map<String, Object>>();
        try {
            lst = JSON.parseObject(jsonString, new 
                         TypeReference<List<Map<String, Object>>>() {});
        } catch (Exception e) {
        }
        return lst;
    }

    /**
     * 获取json中指定的值
     * 
     * @param json  JSON字符串
     * @param key   要获取的值对应的key
     * @return
     */
    public static String getByKey(String json, String key) {
        
        try {
            Map<String, Object> jsonMap = JSON.parseObject(
                    json, new TypeReference<Map<String, Object>>() {});
            if(jsonMap.get(key)==null){
            	log.error("获取key="+key+"出错");
            	return "";
            }
            return jsonMap.get(key).toString();
        } catch (Exception e) {
           log.error("获取key="+key+"出错");
            return "";
        }
       
    }
    
    /**
     * 获取json对应的Map对应
     * 
     * @param json  JSON字符串
     * @return
     */
    public static Map<String, Object> parseMap(String json) {
        
        try {
            return JSON.parseObject(json, new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /****
     * 将string 转换成json数据
     * @param s
     * @return
     */
   public static String string2json(String s) {
       if (s == null)
         return "";
       StringBuilder sb = new StringBuilder();
       for (int i = 0; i < s.length(); i++) {
         char ch = s.charAt(i);
         switch (ch) {
         case '"':
           sb.append("\\\"");
           break;
         case '\\':
           sb.append("\\\\");
           break;
         case '\b':
           sb.append("\\b");
           break;
         case '\f':
           sb.append("\\f");
           break;
         case '\n':
           sb.append("\\n");
           break;
         case '\r':
           sb.append("\\r");
           break;
         case '\t':
           sb.append("\\t");
           break;
         case '/':
           sb.append("\\/");
           break;
         default:
           if (ch >= '\u0000' && ch <= '\u001F') {
             String ss = Integer.toHexString(ch);
             sb.append("\\u");
             for (int k = 0; k < 4 - ss.length(); k++) {
               sb.append('0');
             }
             sb.append(ss.toUpperCase());
           } else {
             sb.append(ch);
           }
         }
       }
       return sb.toString();
   }
   public static String list2json(List<?> list) {
       StringBuilder json = new StringBuilder();
       json.append("[");
       if (list != null && list.size() > 0) {
         for (Object obj : list) {
           json.append(object2json(obj));
           json.append(",");
         }
         json.setCharAt(json.length() - 1, ']');
       } else {
         json.append("]");
       }
       return json.toString();
}
    public static void main(String[] args) {
        
        // 对象转Json
//        UserInfo userinfo = new UserInfo();
//        userinfo.setUserId("1");
//        userinfo.setFileName("zhourabit");
//        String strResult = JsonUtil.toJson(userinfo);
//        log.warn("测试 对象转Json: " + strResult);
        StringUtil   s=new   StringUtil();
        System.out.println(s.stringToDateTime("1996-02-16 08:07:26"));
        boolean   se=s.isEmpty("");
        System.out.println(se);
        
    }
}
